import { Injectable } from '@angular/core'
import { HttpErrorResponse } from '@angular/common/http'
import { throwError, Observable } from 'rxjs'
import { NzMessageService } from 'ng-zorro-antd';
import { Router } from '@angular/router'
import {
  LOGIN_URL,
  HTTP_CODE_AUTHOR_INVALID,
  HTTP_CODE_NETWORK_ERROR,
  HTTP_CODE_FAILURE,
  HTTP_CODE_SERVER_ERROR,
  HTTP_CODE_PARAMS_ERROR,
  HTTP_CODE_PARAMS_ERRORS,
  HTTP_CODE_PARAMS_ERRORY,
  HTTP_CODE_PARAMS_ERRORP,
  HTTP_CODE_PARAMS_ERRORR,
  HTTP_CODE_PARAMS_ERRORO,
  HTTP_CODE_PARAMS_ERRORL,
} from './const'

export type HandleError = () => (error: HttpErrorResponse) => Observable<any>

@Injectable()
export class HttpErrorHandler {
  COOD = {
    '0001': '请求参数错误',
  }
  constructor(
    public messageService: NzMessageService,
    public router: Router
  ) { }

  handleError() {
    const that = this
    const messageSer = this.messageService;
    return (res: HttpErrorResponse) => {
      if (res.status === 200) {
        if (res.error.code !== 200) {
          switch (res.error.code) {
            case HTTP_CODE_PARAMS_ERRORR:
              this.messageService.error('该账号已在其他地方登录，请重新登录')
              break
            case HTTP_CODE_PARAMS_ERRORP:
              this.messageService.error(res.error.message ? res.error.message : '手机号或账户名重复')
              break
            case HTTP_CODE_PARAMS_ERRORS:
              this.messageService.error(res.error.message)
              break
            case HTTP_CODE_PARAMS_ERRORO:
              this.messageService.error('设备未连接,不可下发')
              break
            case HTTP_CODE_PARAMS_ERRORL:
              console.log('设备超时未响应')
              // this.messageService.error('设备超时未响应')
              break
            case HTTP_CODE_PARAMS_ERRORY:
              this.messageService.error('没有登录权限')
              break
            default:
              if (res.error.message) {
                messageSer && messageSer.error(res.error.message)
              }
              return throwError(res)
          }
          return
        }
        switch (res.statusText) {
          case HTTP_CODE_PARAMS_ERROR:
            this.messageService.error(res.error.message)
            break
          case HTTP_CODE_PARAMS_ERRORS:
            console.log(11111)
            this.messageService.error('用户名或密码不正确')
            break
          case HTTP_CODE_PARAMS_ERRORY:
            this.messageService.error('没有登录权限')
            break
          default:
            return throwError(res)
          // this.messageService.error('请求失败')
        }
      }
      return throwError(res)
    }
  }

  errorCode(event) {
    let codeText = this.COOD['event'] ? this.COOD['event'] : '请求状态错误'
    this.messageService.error('返回状态错误')
    return throwError(codeText)
  }
}
